package cn.edu.nju.ws.sview.wyge.relations.adataset.overview.dataGet;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class LeanS {
	static class NODE {
		Integer x, y;

		NODE(int a, int b) {
			x = a;
			y = b;
		}
	}

	static class NODESort implements Comparator<NODE> {
		public NODESort() {
		}

		public int compare(NODE a, NODE b) {
			return a.y - b.y;
		}
	}

	public static void get(ArrayList<concept> concepts, ArrayList<triple> la) {
		// System.out.println("YES");
		for (int i = 0; i < la.size(); ++i) {
			concepts.get(la.get(i).from).state = concept.Associated_S;
			concepts.get(la.get(i).to).state = concept.Associated_S;
		}
		ArrayList<Integer> AS = new ArrayList<Integer>();
		ArrayList<Integer> IS = new ArrayList<Integer>();
		for (int i = 0; i < concepts.size(); ++i) {
			if (concepts.get(i).state == concept.Associated_S)
				AS.add(i);
			else if (concepts.get(i).w > 0)
				IS.add(i);
		}
		int ash[] = new int[AS.size()];
		ArrayList<NODE> nodes = new ArrayList<NODE>();
		for (int i = 0; i < AS.size(); ++i)
			ash[i] = 1;
		for (int i = AS.size() - 1; i >= 0; --i) {
			// System.out.println(i + " " + AS.get(i) + " " + ash[i]);
			// NODE node = ;
			nodes.add(new NODE(i, ash[i]));
			for (int j = 0; j < i; ++j)
				if ((ash[j] <= ash[i])
						&& concepts.get(AS.get(i)).ancestor.contains(AS.get(j)))
					ash[j] = ash[i] + 1;
		}
		// System.out.println(nodes.size());
		Collections.sort(nodes, new NODESort());
		/*
		 * for (int i = 0; i < nodes.size(); ++i)
		 * System.out.println(nodes.get(i).x + " " + nodes.get(i).y);
		 */
		for (int i = 0; i < nodes.size(); ++i)
			for (int j = 0; j < IS.size(); ++j) {
				int a = AS.get(nodes.get(i).x);
				int b = IS.get(j);
				int h = nodes.get(i).y;
				if ((concepts.get(b).state == 0)
						|| (concepts.get(b).state == h))
					if (concepts.get(b).ancestor.contains(a)) {
						concepts.get(b).state = h;
						concepts.get(a).w += concepts.get(b).w;
					}
			}
		for (int i = 0; i < IS.size(); ++i) {
			int w = 0;
			int j;
			int a = IS.get(i);
			if (concepts.get(a).state != 0)
				continue;
			for (j = 0; j < IS.size(); ++j) {
				int b = IS.get(j);
				if (concepts.get(b).state != 0)
					continue;
				if (concepts.get(a).ancestor.contains(b))
					break;
				if (concepts.get(b).ancestor.contains(a))
					w += concepts.get(b).w;
			}
			if (j < IS.size())
				continue;
			concepts.get(a).w += w;
			concepts.get(a).state = concept.Associated_S;
		}
	}
}
